﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;

namespace EComAssignment.Models
{
    public static class MainModel
    {
        public static bool feedbackHandler(string email, string title,string body)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            Feedback feedback = new Feedback()
            {
                feedback_date = DateTime.Now,
                title = title,
                body = body,
                email = email,
                status = "waiting"
            };
            ctx.Feedbacks.InsertOnSubmit(feedback);
            ctx.SubmitChanges();
            return true;
        }

        public static bool saveComment(string username, int proID, string body, bool isReply, int? replyID)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var acc = (from a in ctx.Accounts
                       where a.username == username
                       select a).SingleOrDefault();
            if (acc == null) { return false; }
            Comment cmt = new Comment()
            {
                customer_ID = acc.ID,
                product_ID = proID,
                post_date = DateTime.Now,
                body = body,
                is_reply = isReply,
                reply_ID = replyID
            };
            try
            {
                ctx.Comments.InsertOnSubmit(cmt);
                ctx.SubmitChanges();
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }

        public static bool deleteComment(int cmtID)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var cmt = (from c in ctx.Comments
                       where c.ID == cmtID
                       select c).SingleOrDefault();
            if (cmt == null) { return false; }
            var rp = (from c in ctx.Comments
                      where c.reply_ID == cmt.ID
                      select c);
            try
            {
                if (rp.Count() > 0)
                {
                    ctx.Comments.DeleteAllOnSubmit(rp);
                }
                ctx.Comments.DeleteOnSubmit(cmt);
                ctx.SubmitChanges();
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }

        public static bool confirmCapcha(string remoteIp)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://www.google.com/recaptcha/api/verify");
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";

            return true;
        }

        public static bool saveRating(string username, int proID, int rate, string opinion)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var user = ctx.Accounts.Where(a => a.username == username).SingleOrDefault();
            if (user == null) { return false; }
            var rating = ctx.Ratings.Where(r => r.customer_ID == user.ID && r.product_ID == proID).SingleOrDefault();
            if (rating == null)
            {
                rating = new Rating()
                {
                    customer_ID = user.ID,
                    product_ID = proID,
                };
            }

            rating.rate_date = DateTime.Now;
            rating.status = "waiting";
            rating.rate = rate;
            rating.customer_opinion = opinion;
            
            try
            {
                if (rating.ID == 0)
                {
                    ctx.Ratings.InsertOnSubmit(rating);
                }
                ctx.SubmitChanges();
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }

        public static bool deleteRating(int rateID)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var rate = ctx.Ratings.Where(r => r.ID == rateID).SingleOrDefault();
            if (rate == null) { return false; }
            try
            {
                ctx.Ratings.DeleteOnSubmit(rate);
                ctx.SubmitChanges();
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }

        public static bool addStartSession(string sessionID, string clientIP)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            Visiting vis = new Visiting()
            {
                sessionID = sessionID,
                ClientIP = clientIP,
                start_time = DateTime.Now
            };
            try
            {
                ctx.Visitings.InsertOnSubmit(vis);
                ctx.SubmitChanges();
            }
            catch (Exception e)
            {
                return false;
            }
            return true;

        }

        public static bool addEndSession(string sessionID)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var vis = ctx.Visitings.Where(v => v.sessionID == sessionID);
            if (vis == null) { return false; }
            try
            {
                if (vis.Count() > 0)
                {
                    vis.OrderByDescending(v => v.start_time).First().end_time = DateTime.Now;
                    ctx.SubmitChanges();
                }
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }

        public static Dictionary<string, int> visitCount()
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var vis = (from v in ctx.Visitings
                       select v);
            Dictionary<string, int> count = new Dictionary<string, int>();
            var today = vis.Where(v => v.start_time > DateTime.Today).Count();
            var yesterday = vis.Where(v => v.start_time > DateTime.Today.AddDays(-1) && v.start_time < DateTime.Today).Count();
            count.Add("Hôm nay:", today);
            count.Add("Hôm qua:", yesterday);
            count.Add("Tất cả:", vis.Count());
            return count;
        }

        public static string ConvertToVietnameseNotSignature(string strVietnamese)
        {
            const string FindText = "áàảãạâấầẩẫậăắằẳẵặđéèẻẽẹêếềểễệíìỉĩịóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵÁÀẢÃẠÂẤẦẨẪẬĂẮẰẲẴẶĐÉÈẺẼẸÊẾỀỂỄỆÍÌỈĨỊÓÒỎÕỌÔỐỒỔỖỘƠỚỜỞỠỢÚÙỦŨỤƯỨỪỬỮỰÝỲỶỸỴ#%&*:|.";
            const string ReplText = "aaaaaaaaaaaaaaaaadeeeeeeeeeeeiiiiiooooooooooooooooouuuuuuuuuuuyyyyyAAAAAAAAAAAAAAAAADEEEEEEEEEEEIIIIIOOOOOOOOOOOOOOOOOUUUUUUUUUUUYYYYY       ";
            int index = -1;
            while ((index = strVietnamese.IndexOfAny(FindText.ToCharArray())) != -1)
            {
                int index2 = FindText.IndexOf(strVietnamese[index]);
                strVietnamese = strVietnamese.Replace(strVietnamese[index], ReplText[index2]);
            }
            return strVietnamese;
        }

        public static bool isUserComment(int cmtID, string username)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var cmt = ctx.Comments.Where(c => c.ID == cmtID).SingleOrDefault();
            if (cmt == null) { return false; }
            return cmt.Account.username.Equals(username);
        }
    }
}